package com.yujing.yview

import android.annotation.SuppressLint
import android.app.Activity
import android.os.Build
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.appcompat.widget.AppCompatEditText
import androidx.core.content.ContextCompat
import com.yujing.yview.base.YBaseDialog
import com.yujing.yview.constants.Constants
import com.yujing.yview.databinding.DialogGradingSoftKeyboardVerticalBinding
import java.util.Timer
import java.util.TimerTask

/**
 * 等级级软键盘
 *
 * @author yujing 2019年12月17日14:04:19
 */
/*
用法
val dialog = GradingSoftKeyboard(this)
dialog.setSoftKeYListener1 { Grade, GradeName ->
    dialog.dismiss()
    //逻辑操作
    showSpeak("$Grade $GradeName")
}
dialog.show()
 */
class GradingSoftKeyboardVertical(activity: Activity) : YBaseDialog<DialogGradingSoftKeyboardVerticalBinding>(activity, R.layout.dialog_grading_soft_keyboard_vertical, android.R.style.Theme_DeviceDefault_Dialog_NoActionBar) {
    private var viewKeys: Array<LinearLayout> = arrayOf()    //全部按键
    private var viewNames: Array<TextView> = arrayOf()  //全部按键名称
    private var viewTips: Array<TextView> = arrayOf()    //全部按键提示
    private var deleteTimer: Timer? = null //长按删除
    private var find = false //当前输入的内容是否在映射表（gradingTemps）中找到
    private val controlKeys: List<String> = mutableListOf("返回", "", "确定", "删除") //控制键
    private val numberKeys: List<String> = mutableListOf("1", "2", "3", "4") //数字键

    var okListener: ((grade: String, gradeName: String) -> Unit)? = null //监听

    //初始化完成
    var initCompleteListener: ((DialogGradingSoftKeyboardVerticalBinding) -> Unit)? = null

    init {
        fullscreen = true
        widthPixels = 0.85f
        heightPixels = 0.7f
        fillColor = ContextCompat.getColor(activity, R.color.fill_background)
    }

    //文字大小比例
    var textSizeScale = 1.0f
    private val names = arrayOf(
        "BK", "BV", "BL", "BF", "1", "删除",
        "CXK", "C3V", "CL", "CF", "2", "返回",
        "HF", "X2V", "XL", "XF", "3", "",
        "S", "BR", "GY", "JW", "4", "确定"
    )
    private val tips = arrayOf(
        "上杂", "上微青", "上柠", "上桔", "", "",
        "中下杂", "中微三", "中柠", "中桔", "", "",
        "完熟", "下微二", "下柠", "下桔", "", "",
        "光滑", "上红棕", "青黄", "级外", "", ""
    )

    override fun init() {
        binding.tvContent.addTextChangedListener(watcher)
        //点击不弹出输入法
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) binding.tvContent.showSoftInputOnFocus = false
        viewKeys = arrayOf(
            binding.key11, binding.key12, binding.key13, binding.key14, binding.key15, binding.key16,
            binding.key21, binding.key22, binding.key23, binding.key24, binding.key25, binding.key26,
            binding.key31, binding.key32, binding.key33, binding.key34, binding.key35, binding.key36,
            binding.key41, binding.key42, binding.key43, binding.key44, binding.key45, binding.key46
        )
        viewNames = arrayOf(
            binding.tv11Name, binding.tv12Name, binding.tv13Name, binding.tv14Name, binding.tv15Name, binding.tv16Name,
            binding.tv21Name, binding.tv22Name, binding.tv23Name, binding.tv24Name, binding.tv25Name, binding.tv26Name,
            binding.tv31Name, binding.tv32Name, binding.tv33Name, binding.tv34Name, binding.tv35Name, binding.tv36Name,
            binding.tv41Name, binding.tv42Name, binding.tv43Name, binding.tv44Name, binding.tv45Name, binding.tv46Name
        )
        viewTips = arrayOf(
            binding.tv11Tip, binding.tv12Tip, binding.tv13Tip, binding.tv14Tip, binding.tv15Tip, binding.tv16Tip,
            binding.tv21Tip, binding.tv22Tip, binding.tv23Tip, binding.tv24Tip, binding.tv25Tip, binding.tv26Tip,
            binding.tv31Tip, binding.tv32Tip, binding.tv33Tip, binding.tv34Tip, binding.tv35Tip, binding.tv36Tip,
            binding.tv41Tip, binding.tv42Tip, binding.tv43Tip, binding.tv44Tip, binding.tv45Tip, binding.tv46Tip
        )
        //---------------------------缩放---------------------------
        binding.tvTitle.textSize = px2sp(binding.tvTitle.textSize.toInt()) * textSizeScale
        binding.tvContent.textSize = px2sp(binding.tvContent.textSize.toInt()) * textSizeScale
        binding.tvContentTips.textSize = px2sp(binding.tvContentTips.textSize.toInt()) * textSizeScale
        binding.tvReName.textSize = px2sp(binding.tvReName.textSize.toInt()) * textSizeScale
        binding.tvReNameTips.textSize = px2sp(binding.tvReNameTips.textSize.toInt()) * textSizeScale
        binding.tvName.textSize = px2sp(binding.tvName.textSize.toInt()) * textSizeScale
        binding.tvNameTips.textSize = px2sp(binding.tvNameTips.textSize.toInt()) * textSizeScale
        //---------------------------缩放---------------------------
        for (item in viewNames) {
            item.textSize = px2sp(item.textSize.toInt()) * textSizeScale
        }
        for (item in viewTips) {
            item.textSize = px2sp(item.textSize.toInt()) * textSizeScale
        }
        //命名,设置监听
        for (i in names.indices) {
            //设置名称文字
            viewNames[i].text = names[i]
            //设置提示文字
            viewTips[i].text = tips[i]
            //设置隐藏提示文字
            if (tips[i].isEmpty()) viewTips[i].visibility = View.GONE
            //设置监听，如果是控制键controlKey方法
            val key = names[i]
            if (controlKeys.contains(key)) {
                controlKey(i)
            } else {
                inputKey(i)
            }
        }
        initCompleteListener?.invoke(binding)
    }

    /**
     * 控制键
     *
     * @param index 按键序号
     */
    @SuppressLint("ClickableViewAccessibility")
    private fun controlKey(index: Int) {
        val key = names[index]
        viewKeys[index].isClickable = true //设置为true才能监听到MotionEvent.ACTION_UP事件
        if ("删除" == key) {
            viewNames[index].setTextColor(-0x999a)
            viewKeys[index].setOnTouchListener { v: View, event: MotionEvent ->
                touchEvent(v, binding.tvContent, event)
                false
            }
        } else if ("确定" == key) {
            viewNames[index].setTextColor(-0xff0100)
            viewKeys[index].setOnClickListener { v: View? ->
                if (binding.tvReName.length() > 0 && okListener != null) {
                    okListener?.invoke(binding.tvReName.text.toString(), binding.tvName.text.toString())
                    dismiss()
                }
            }
        } else if ("返回" == key) {
            viewNames[index].setTextColor(-0x6667)
            viewKeys[index].setOnClickListener { v: View? -> dismiss() }
        } else if ("" == key) {
        }
    }

    /**
     * 输入键
     *
     * @param index 键序号
     */
    private fun inputKey(index: Int) {
        val key = names[index]
        //如果是1234直接添加,否则重置字符串
        if (numberKeys.contains(key)) {
            //如果长度小于4才能添加,当前名字没在映射表中找到
            viewKeys[index].setOnClickListener { v: View? ->
                if (binding.tvContent.text != null && binding.tvContent.text!!.length < 4 && !find) {
                    binding.tvContent.setText(java.lang.String.format("%s%s", binding.tvContent.text, key))
                }
            }
        } else {
            viewKeys[index].setOnClickListener { v: View? -> binding.tvContent.setText(key) }
        }
    }

    //当前输入的内容
    private fun currentInput(value: String) {
        find = false
        for (i in Constants.gradingTemps.indices) {
            val gradName = Constants.gradingTemps[i]
            if (gradName == value) {
                find = true
                val gradingCode = Constants.gradingCodes[i]
                val gradingName = Constants.gradingNames[i]
                binding.tvReName.text = gradingCode
                binding.tvName.text = gradingName
                binding.tvName.setTextColor(ContextCompat.getColor(context, R.color.correct))
            }
        }
        if (!find) {
            binding.tvReName.text = ""
            //如果显示的有，但是有没有找到就显示等级不存在
            binding.tvName.text = if (value.length == 0) "" else "等级不存在"
            binding.tvName.setTextColor(ContextCompat.getColor(context, R.color.error))
        }
    }

    /**
     * 删除键长按监听
     *
     * @param v        按的view
     * @param editText 处理的view——editText
     * @param event    事件
     */
    private fun touchEvent(v: View, editText: AppCompatEditText, event: MotionEvent) {
        if (event.action == MotionEvent.ACTION_DOWN) {
            Log.d("ACTION_DOWN", "ACTION_DOWN")
            deleteTimer = Timer()
            //500毫秒后开始,每隔100毫秒执行一次
            deleteTimer?.schedule(object : TimerTask() {
                override fun run() {
                    delete(editText)
                }
            }, 500, 100)
        } else if (event.action == MotionEvent.ACTION_UP) {
            Log.d("ACTION_UP", "ACTION_UP")
            delete(editText)
            if (null != deleteTimer) {
                deleteTimer?.cancel()
                deleteTimer = null
            }
        }
    }

    //删除尾巴字符串
    private fun delete(editText: AppCompatEditText) {
        //按下
        if (editText.text != null && editText.text.toString().isNotEmpty()) {
            val content = editText.text.toString()
            //如果最后一位是1234则删除最后一位
            if (numberKeys.contains(content.substring(content.length - 1))) {
                activity.runOnUiThread { editText.setText(content.substring(0, content.length - 1)) }
            } else {
                activity.runOnUiThread { editText.setText("") }
            }
        }
    }

    //光标移动到最后
    private val watcher: TextWatcher = object : TextWatcher {
        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
            currentInput(s.toString())
        }

        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
        override fun afterTextChanged(s: Editable) {
            binding.tvContent.setSelection(binding.tvContent.length())
        }
    }
}